package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.OmcNursingLogMapper;
import com.csun.cmny.provider.exceptions.OmcBizException;
import com.csun.cmny.provider.model.domain.OmcNursingLog;
import com.csun.cmny.provider.model.domain.OmcSchedul;
import com.csun.cmny.provider.model.dto.NursingLogQueryDto;
import com.csun.cmny.provider.model.vo.NursinglogDetailVo;
import com.csun.cmny.provider.model.vo.OmcUserVo;
import com.csun.cmny.provider.model.vo.RpcRoleVo;
import com.csun.cmny.provider.model.vo.RpcUserVo;
import com.csun.cmny.provider.pojo.Oldman;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.MenuTimeUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


@Slf4j
@Service
public class OmcNursingLogServiceImpl extends BaseService<OmcNursingLog> implements OmcNursingLogService {

    @Resource
    private OmcNursingLogMapper omcNursingLogMapper;

    @Resource
    private UacRpcService uacRpcService;

    @Resource
    private OmcGroupService omcGroupService;

    @Resource
    private OmcScheduleService omcScheduleService;

    @Resource
    private OldmanService oldmanService;

    @Override
    public OmcNursingLog queryByDate(NursingLogQueryDto nursingLogQueryDto, LoginAuthDto loginAuthDto) throws ParseException {

        //设置护工组Id
        int nursingGroupId = getNursingGroupId(nursingLogQueryDto.getNursingGroupId(), loginAuthDto);

        //创建查询对象
        OmcNursingLog omcNursingLogQuery = new OmcNursingLog();
        BeanUtils.copyProperties(nursingLogQueryDto, omcNursingLogQuery);
        omcNursingLogQuery.setNursingGroupId(nursingGroupId);

        OmcNursingLog omcNursingLog = omcNursingLogMapper.selectOne(omcNursingLogQuery);

//        //查询日志list
//        List<OmcNursingLog> omcNursingLogList = omcNursingLogMapper.select(omcNursingLogQuery);

        //当无查询结果时，查询排班计划情况
        if (omcNursingLog == null) {

            //创建排班查询对象
            OmcSchedul omcSchedulQuery = new OmcSchedul();
            omcSchedulQuery.setNursingGroupId(nursingGroupId);
            omcSchedulQuery.setGroupId(omcNursingLogQuery.getGroupId());
            String week = MenuTimeUtil.getDays(nursingLogQueryDto.getDate()).get(1) + MenuTimeUtil.getDays(nursingLogQueryDto.getDate()).get(0);

            //将转换好的周数放入查询对象
            omcSchedulQuery.setWeek(Integer.parseInt(week));

            //查询
            List<OmcSchedul> omcSchedulList = omcScheduleService.select(omcSchedulQuery);

            //当无查询结果时，返回1
            if (omcSchedulList.size() <= 0 || omcSchedulList == null) {
                throw new OmcBizException(ErrorCodeEnum.OMC10036001);
                //有查询结果时，判断排班计划的审批状态  0- 未审批 1-审批未通过 2-审批通过
            } else {
                int status = omcSchedulList.get(0).getStatus();
                if (status == 0 || status == 1) {
                    throw new OmcBizException(ErrorCodeEnum.OMC10036002);
                }
            }
        }
        return omcNursingLog;
    }

    @Override
    public List<OmcNursingLog> selectMenus(NursingLogQueryDto nursingLogQueryDto, LoginAuthDto loginAuthDto) {
        return null;
    }

    @Override
    public List<OmcNursingLog> querySoreCareOldList(NursingLogQueryDto nursingLogQueryDto, LoginAuthDto loginAuthDto) {
        return null;
    }

    @Override
    public List<OmcNursingLog> getNursingLog(NursingLogQueryDto nursingLogQueryDto, LoginAuthDto loginAuthDto) {
        return null;
    }

    @Override
    public Integer saveNursingLog(OmcNursingLog omcNursingLog, LoginAuthDto loginAuthDto) {

        int nursingGroupId = getNursingGroupId(omcNursingLog.getNursingGroupId(), loginAuthDto);

        //放入操作者信息
        omcNursingLog.setNursingGroupId(nursingGroupId);
        omcNursingLog.setGroupId(loginAuthDto.getGroupId());
        omcNursingLog.setUpdateInfo(loginAuthDto);


        //先查询当日是否有护理日志
        selectOne(omcNursingLog);
        OmcNursingLog nursingLogQuery = new OmcNursingLog();
        nursingLogQuery.setDate(omcNursingLog.getDate());
        nursingLogQuery.setNursingGroupId(omcNursingLog.getNursingGroupId());
        OmcNursingLog result = selectOne(nursingLogQuery);

        if (result == null) {
            return omcNursingLogMapper.insertSelective(omcNursingLog);
        } else {
            omcNursingLog.setId(result.getId());
            return omcNursingLogMapper.updateByPrimaryKeySelective(omcNursingLog);
        }

    }

    @Override
    public Integer dccNursingLog() {
        //1 ν 0 ν 无   μ   2 ν 0 ν 刘桂芝：儿子送来藕汤     μ     3 ν 0 ν 廖秋英：儿子送来藕汤，已吃吴汉英：儿子送来银耳汤，已吃
        List<OmcNursingLog> nursingLogList = selectAll();
        int count = 0;
        for (OmcNursingLog nursingLog : nursingLogList) {
            String meal = dccMeal(nursingLog);
            String disinfection = dccDisinfection(nursingLog);
            String basicnursing = dccInfo(nursingLog.getBasicNursing());
            String mouthcare = dccInfo(nursingLog.getMouthCare());
            String bedsorecare = dccInfo(nursingLog.getBedsoreCare());
            String recoveryTrain = dccInfo(nursingLog.getRecoveryTrain());

            nursingLog.setMeal(meal);
            nursingLog.setDisinfection(disinfection);
            nursingLog.setBasicNursing(basicnursing);
            nursingLog.setMouthCare(mouthcare);
            nursingLog.setBedsoreCare(bedsorecare);
            nursingLog.setRecoveryTrain(recoveryTrain);

            count += update(nursingLog);
        }
        return count;
    }

    @Override
    public Integer dccDisinfection() {
        List<OmcNursingLog> nursingLogList = selectAll();
        for(OmcNursingLog nursingLog : nursingLogList){
        String finallyDis = "";
//        OmcNursingLog nursingLog = selectByKey(256L);
        if (nursingLog.getDisinfection() != null && !nursingLog.getDisinfection().equals("")) {
                //1-1-1-0-潘荣萍,1-3-1-0-邓爱华,1-3-0-0-潘荣萍,1-5-0-0-邓爱华;2-4-0-0-0,2-5-1-0-0,2-0-0-0-0,2-0-0-0-0;3-0-0-0-0,3-0-0-0-0,3-0-0-0-0,3-0-0-0-0
                String disinfections[] = nursingLog.getDisinfection().split(";");
                for (int i = 0; i < disinfections.length; i++) {
                    String str[] = disinfections[i].split(",");
                    String newDisinfection = "";
                    //某个类型的消毒记录集合
                    for (int j = 0; j < str.length; j++) {
                        String arr[] = str[j].split("-");
                            switch (arr[1]){
                                //冲洗
                                case "1":
                                    arr[1] = "8";
                                    break;
                                case "2":
                                    arr[1] = "9";
                                    break;
                                case "3":
                                    arr[1] = "10";
                                    break;
                                case "4":
                                    arr[1] = "11";
                                    break;
                                case "5":
                                    arr[1] = "12";
                                    break;
                                case "6":
                                    arr[1] = "13";
                                    break;
                                case "7":
                                    arr[1] = "14";
                                    break;
                                default:
                                    arr[1] = "0";
                                    break;
                            }
                            switch (arr[2]){
                                //冲洗
                                case "1":
                                    arr[2] = "15";
                                    break;
                                case "2":
                                    arr[2] = "16";
                                    break;
                                case "3":
                                    arr[2] = "17";
                                    break;
                                case "4":
                                    arr[2] = "18";
                                    break;
                                case "5":
                                    arr[2] = "19";
                                    break;
                                default:
                                    arr[2] = "0";
                                    break;
                            }
                        str[j] = arr[0] + "-" + arr[1] + "-" + arr[2] + "-" + arr[3] + "-" + arr[4] + "";
                    }
                    String dis = "";
                    for (int b = 0; b < str.length; b++) {
                        if (b == str.length - 1) {
//                            int i1 = (b % 3) + 1;
//                            dis += str[b] + "," + i1 + "-0-0-0-0:请选择";
                            dis += str[b];
                        } else {
                            dis += str[b] + ",";
                        }
                    }
                    disinfections[i] = dis;
                }
                for (int c = 0; c < disinfections.length; c++) {
                    if (c == disinfections.length - 1) {
                        finallyDis += disinfections[c];
                    } else {
                        finallyDis += disinfections[c] + ";";
                    }
                }
            }
            nursingLog.setDisinfection(finallyDis);
            update(nursingLog);
        }
        return 0;
    }

/*    @Override
    public List<OmcNursingLog> getNursingLog(NursingLogQueryDto nursingLogQueryDto, LoginAuthDto loginAuthDto) {

        int nursingGroupId = getNursingGroupId(nursingLogQueryDto.getNursingGroupId(),loginAuthDto);

        //创建查询对象
        OmcNursingLog omcNursingLogQuery = new OmcNursingLog();
        omcNursingLogQuery.setNursingGroupId(nursingGroupId);
        List<OmcNursingLog> omcNursingLogList = select(omcNursingLogQuery);

        return omcNursingLogList;
    }*/

    //校验护工组id
    public int getNursingGroupId(Integer omcNurisngGroupId, LoginAuthDto loginAuthDto) {

        //查询用户身份
        List<RpcRoleVo> rpcRoleVos = uacRpcService.queryRoleListByUserId(loginAuthDto.getUserId());

        //定义班组id
        Integer nursingGroupId = 0;

        for (RpcRoleVo vo : rpcRoleVos) {
            //1.身份为护工时，班组id为护工所在的班组id
            if (vo.getRoleCode().equals("nursing")) {
                nursingGroupId = omcGroupService.selectNuringGroupIdByUserId(loginAuthDto.getUserId()).intValue();
                //2.身份为服务部长时，班组id为服务部长指定的id
            } else {
                nursingGroupId = omcNurisngGroupId;
            }
        }
        if (nursingGroupId == null || nursingGroupId == 0) {
            throw new OmcBizException(ErrorCodeEnum.OMC10035006);
        }

        return nursingGroupId;

    }

    public String dccMeal(OmcNursingLog nursingLog) {
        if (nursingLog.getMeal() != null && !nursingLog.getMeal().equals("") && !nursingLog.getMeal().contains(":")) {
            String meals[] = nursingLog.getMeal().split("μ");
            for (int i = 0; i < meals.length; i++) {
                String oldmanIdAndName = "";
                //单个膳食记录
                String str[] = meals[i].split("ν");
                //获取老人id集合，默认插入的是0，如果是0则代表没有数据
                if (!(str[1].equals("0")) && !(str[1].equals(""))) {
                    String oldmanIdArray[] = str[1].split("-");
                    for (int k = 0; k < oldmanIdArray.length; k++) {
                        Oldman o = new Oldman();
                        o.setOldmanId(Integer.parseInt(oldmanIdArray[k]));
                        o = oldmanService.selectByOld(o);
                        if (o != null) {
                            oldmanIdArray[k] = o.getOldmanId().toString() + ":" + o.getOldName();
                        } else {
                            oldmanIdArray[k] = "0";
                        }
                    }
                    for (int a = 0; a < oldmanIdArray.length; a++) {
                        if (i == oldmanIdArray.length - 1) {
                            oldmanIdAndName += oldmanIdArray[a];
                        } else {
                            oldmanIdAndName += oldmanIdArray[a] + "-";
                        }
                    }
                } else {
                    oldmanIdAndName = "0";
                }
                meals[i] = str[0] + "ν" + oldmanIdAndName + "ν" + str[2];
            }
            String meal = meals[0] + "μ" + meals[1] + "μ" + meals[2];
            return meal;
        }
        return "";
    }

    public String dccDisinfection(OmcNursingLog nursingLog) {
        if (nursingLog.getDisinfection() != null && !nursingLog.getDisinfection().equals("")) {
            //1-1-1-0-潘荣萍,1-3-1-0-邓爱华,1-3-0-0-潘荣萍,1-5-0-0-邓爱华;2-4-0-0-0,2-5-1-0-0,2-0-0-0-0,2-0-0-0-0;3-0-0-0-0,3-0-0-0-0,3-0-0-0-0,3-0-0-0-0
            String disinfections[] = nursingLog.getDisinfection().split(";");
            for (int i = 0; i < disinfections.length; i++) {
                String str[] = disinfections[i].split(",");
                String newDisinfection = "";
                //某个类型的消毒记录集合
                for (int j = 0; j < str.length; j++) {
                    //消毒记录
                    String arr[] = str[j].split("-");
                    if (!arr[4].equals("0")) {
                        int flag = 0;
                        char[] ch = arr[4].toCharArray();
                        for (char c : ch) {
                            if (!(c >= '0' && c <= '9')) {
                                flag = 1;
                            }
                        }
                        if (flag == 0) {
                            Long nursingId = Long.parseLong(arr[4]);
                            List<OmcUserVo> omcUserVos = uacRpcService.queryOmcUserListByUserIds(Lists.newArrayList(nursingId));
                            if (omcUserVos.size() > 0) {
                                arr[4] = omcUserVos.get(0).getUserId().toString() + ":" + omcUserVos.get(0).getUserName();
                            } else {
                                arr[4] = arr[4] + ":已离职护工";
                            }
                        } else {
                            arr[4] = "9999:" + arr[4];
                        }
                        str[j] = arr[0] + "-" + arr[1] + "-" + arr[2] + "-" + arr[3] + "-" + arr[4];
                    }else{
                        str[j] = arr[0] + "-" + arr[1] + "-" + arr[2] + "-" + arr[3] + "-" + arr[4] + ":请选择";
                    }
                }
                String dis = "";
                for (int b = 0; b < str.length; b++) {
                    if (b == str.length - 1) {
                        dis += str[b];
                    } else {
                        dis += str[b] + ",";
                    }
                }
                disinfections[i] = dis;
            }
            String finallyDis = "";
            for (int c = 0; c < disinfections.length; c++) {
                if (c == disinfections.length - 1) {
                    finallyDis += disinfections[c];
                } else {
                    finallyDis += disinfections[c] + ";";
                }
            }
            return finallyDis;
        }
        return "";
    }

    public String dccInfo(String info){
        //获取服务数组
        if(info != null && !info.equals("")){
            String infos[] = info.split(";");
            for(int i=0;i<=infos.length-1;i++){
                if(!infos[i].equals("0")){
                    //服务
                    String str[] = infos[i].split(",");
                    //第二个存放的是负责人id
                    //判断存的是id还是姓名
                    String userString = str[1];
                    if(!userString.equals("0") && !userString.equals("")){
                        int flag = 0;
                        char[] ch = userString.toCharArray();
                        for (char c : ch) {
                            if (!(c >= '0' && c <= '9')) {
                                flag = 1;
                            }
                        }
                        if (flag == 0) {
                            Long nursingId = Long.parseLong(userString);
                            List<OmcUserVo> omcUserVos = uacRpcService.queryOmcUserListByUserIds(Lists.newArrayList(nursingId));
                            if (omcUserVos.size() > 0) {
                                userString = omcUserVos.get(0).getUserId().toString() + ":" + omcUserVos.get(0).getUserName();
                            } else {
                                userString = userString + ":已离职护工";
                            }
                        } else {
                            userString = "9999:" + userString;
                        }
                    }else{
                        userString = "9999:请选择";
                    }
                    //获取老人数组
                    String oldMans[] = str[0].split("-");
                    //老人姓名集合
                    List<String> oldmanNameList = Lists.newArrayList();
                    String oldmanString = "";
                    for(int j=0; j < oldMans.length ; j++){
                        if (!oldMans[j].equals("0")) {
                            int oldmanId = Integer.parseInt(oldMans[j]);
                            Oldman o = new Oldman();
                            o.setOldmanId(oldmanId);
                            o = oldmanService.selectByOld(o);
                            if(o != null){
                                oldMans[j] = o.getOldmanId().toString() + ":" + o.getOldName();
                            }
                            if (j == oldMans.length - 1) {
                                oldmanString +=oldMans[j];
                            } else {
                                oldmanString +=oldMans[j] + "-";
                            }
                        }
                    }
                    if(oldmanString.equals("")){
                        infos[i] = "0," + userString;
                    }else{
                        infos[i] = oldmanString + "," + userString;
                    }
                }
            }
            String finalString = "";
            for (int i=0;i < infos.length ; i++) {
                if (i == infos.length - 1) {
                    finalString += infos[i];
                } else {
                    finalString += infos[i] + ";";
                }
            }
            return finalString;
        }
        return "";
    }
}
